package com.mynetwork.activity;

import org.json.JSONException;

import com.mynetwork.R;
import com.mynetwork.data.AppData;
import com.mynetwork.data.AppUniqueIdManager;
import com.mynetwork.data.ContentManager;
import com.mynetwork.data.NetworkManager;
import com.mynetwork.data.OnNetworkListener;
import com.mynetwork.utils.SharedPrefHelper;
import com.mynetwork.utils.Size;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends ActivityBase {
	private static final String TAG = "MainActivity";
	private int mIsStep = 0;
	private boolean mIsInit = false;
	private boolean mIsRun = false;
	
	private int NetApiCount = 1;
	
	private LocationManager locationManager;
	private String provider;
	private Location location;
	
	public static double lat = 0;
	public static double lng = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(createMainLayout());
        loadGps();
        Log.e("현재위치정보", "위도 == " + location.getLatitude() + "    경도 === " + location.getLongitude());
        lat = location.getLatitude();
        lng = location.getLongitude();
        AppData.init(this);
        if (TextUtils.isEmpty(AppData.APP_ID)) {
	        (new AppUniqueIdManager()).download(this,new OnNetworkListener(){
				@Override
				public void onSuccess(NetworkManager mgr) {
					SharedPrefHelper.setAppId(MainActivity.this, AppData.APP_ID);
					init();
				}
				@Override
				public void onError(NetworkManager mgr) {
					showDialog(ActivityBase.DIALOG_NETWORK_FAIL);
				}
			});
        } else {
        	init();
        }
    }

    private void init() {
        ContentManager.getInstance().download(this, mOnNetworkListener);
        m_startActivityHandler.sendEmptyMessageDelayed(0, 5000);
    }
    
    @Override
	public void onBackPressed() {
		if (mIsInit)
			super.onBackPressed();
	}



	Handler m_startActivityHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			Log.e(TAG,"KDS3393_Intro m_startActivityHandler mIsInit = " + mIsInit);
			if (mIsInit) {
				run();
			} else {
				mIsInit = true;
			}
		}
	};
	
    private OnNetworkListener mOnNetworkListener = new OnNetworkListener() {
		@Override
		public void onSuccess(NetworkManager mgr) {
			Log.e(TAG,"KDS3393_NetSuccess = " + mgr);
			mIsStep++;
			txt.setText("Intro 화면" + mIsStep + "/" + NetApiCount);
			if (mIsStep >= NetApiCount) {
		    	ContentManager.getInstance().setPrefTimeStamp(MainActivity.this);
				Log.e(TAG,"KDS3393_Intro onSuccess mIsInit = " + mIsInit);
				if (mIsInit) {
					run();
				} else {
					mIsInit = true;
				}
			}
		}
		@Override
		public void onError(NetworkManager mgr) {
			mIsStep++;
			txt.setText("Intro 화면" + mIsStep + "/" + NetApiCount);
			if (mNetworkFailDialog == null && mgr instanceof ContentManager) {
				if (ContentManager.getInstance().getContentList() == null || 
						ContentManager.getInstance().getContentList().size() <= 0)
				showDialog(ActivityBase.DIALOG_NETWORK_FAIL);
			}
			if (mIsStep >= NetApiCount) {
				Log.e(TAG,"KDS3393_Intro onError mIsInit = " + mIsInit);
				if (mIsInit) {
					run();
				} else {
					mIsInit = true;
				}
			}
			Log.e(TAG,"KDS3393_network fail = " + mgr);
		}
	};
	
	private TextView txt;
    private RelativeLayout createMainLayout() {
    	RelativeLayout main = new RelativeLayout(this);
    	txt = new TextView(this);
   		txt.setGravity(Gravity.CENTER);
   		txt.setTextSize(30);
   		main.addView(txt);
    	return main;
    }
    
    private void run() {
		Log.e(TAG,"KDS3393_mIsRun " + mIsRun);
		if (mNetworkFailDialog != null) {
			return;
		}
		
		if (!mIsRun) {
			mIsRun = true;
			finish();
			Intent intent = new Intent(MainActivity.this, SecondActivity.class);
			startActivity(intent);
		}
	}
    
    private boolean result = false;
    
    private void loadGps(){
    	String context = Context.LOCATION_SERVICE;
    	locationManager = (LocationManager) getSystemService(context);
    	
    	Criteria criteria = new Criteria();
    	criteria.setAccuracy(Criteria.ACCURACY_FINE);
    	criteria.setPowerRequirement(Criteria.POWER_LOW);
    	criteria.setAltitudeRequired(false);
    	criteria.setBearingRequired(false);
    	criteria.setSpeedRequired(false);
    	criteria.setCostAllowed(true);
    	
    	provider = locationManager.getBestProvider(criteria, true);
    	if (provider == null) {
			result =  chkGpsService();
			if (result) {
				loadGps();
			}
		}else {
			location = locationManager.getLastKnownLocation(provider);
			locationManager.requestLocationUpdates(provider, 1000, 5, loclistener);
			
			if (location == null) {
				location = locationManager.getLastKnownLocation(provider);
				if (location == null) {
					AlertDialog.Builder adb = new AlertDialog.Builder(this);
					adb.setPositiveButton("ok", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}
					});
					adb.setTitle("정보받아오기 실패");
					adb.setMessage("실패");
					adb.show();
				}
			}
		}
    }
    
    private final LocationListener loclistener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			
		}
	};
    
    private boolean chkGpsService(){
    	String gs = android.provider.Settings.Secure.getString(getContentResolver(), 
    			android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    	
    	if (gs.indexOf("gps",0) < 0) {
			AlertDialog.Builder gsDialog = new AlertDialog.Builder(this);
			gsDialog.setTitle("GPS가 꺼져있다");
			gsDialog.setMessage("설정 바꿔");
			gsDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					intent.addCategory(intent.CATEGORY_DEFAULT);
					startActivity(intent);
				}
			}).create().show();
			return false;
		}else {
			return true;
		}
    }
}
